﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace SilverMindMap.Core.Model
{
    public class MindMapObserver : IDisposable
    {
        private bool _disposed;
        private readonly MindMap _mindMap;
        private readonly IDictionary<Node, NodeObserver> _nodeObservers;

        public MindMapObserver(MindMap mindMap)
        {
            Guard.ArgumentNotNull(mindMap, "mindMap");

            _mindMap = mindMap;
            _nodeObservers = new Dictionary<Node, NodeObserver>();
            ((INotifyCollectionChanged)_mindMap.Nodes).CollectionChanged += OnNodesChanged;

            foreach (var node in _mindMap.Nodes)
                OnNodeAdded(node);
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            ((INotifyCollectionChanged)_mindMap.Nodes).CollectionChanged -= OnNodesChanged;

            foreach (var nodeObserver in _nodeObservers.Values)
                nodeObserver.Dispose();

            _disposed = true;
        }
        
        private void CheckNotDisposed()
        {
            if (_disposed)
                throw new ObjectDisposedException("MindMapObserver");
        }

        private void OnNodesChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            CheckNotDisposed();

            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    OnNodeAdded((Node)e.NewItems[0]);
                    break;

                case NotifyCollectionChangedAction.Remove:
                    OnNodeRemoved((Node)e.OldItems[0]);
                    break;

                case NotifyCollectionChangedAction.Replace:
                    OnNodeRemoved((Node)e.OldItems[0]);
                    OnNodeAdded((Node)e.NewItems[0]);
                    break;

                case NotifyCollectionChangedAction.Reset:
                    throw new NotImplementedException("MindMapObserver does not support Reset notifications from the MindMap");
            }
        }

        protected virtual void OnNodeAdded(Node newNode)
        {
            var nodeObserver = new NodeObserver(newNode, this);
            _nodeObservers[newNode] = nodeObserver;

            var handler = this.NodeAdded;
            if (handler != null)
                handler(this, new NodeEventArgs(newNode));
        }

        public event EventHandler<NodeEventArgs> NodeAdded;

        protected virtual void OnNodeRemoved(Node oldNode)
        {
            var handler = this.NodeRemoved;
            if (handler != null)
                handler(this, new NodeEventArgs(oldNode));

            var nodeObserver = _nodeObservers[oldNode];
            _nodeObservers.Remove(oldNode);
            nodeObserver.Dispose();
        }

        public event EventHandler<NodeEventArgs> NodeRemoved;

        protected virtual void OnLinkAdded(Link newLink)
        {
            var handler = this.LinkAdded;
            if (handler != null)
                handler(this, new LinkEventArgs(newLink));
        }

        public event EventHandler<LinkEventArgs> LinkAdded;

        protected virtual void OnLinkRemoved(Link oldLink)
        {
            var handler = this.LinkRemoved;
            if (handler != null)
                handler(this, new LinkEventArgs(oldLink));
        }

        public event EventHandler<LinkEventArgs> LinkRemoved;

        private class NodeObserver : IDisposable
        {
            private bool _disposed = false;
            private readonly Node _node;
            private readonly MindMapObserver _parentObserver;

            public NodeObserver(Node node, MindMapObserver parentObserver)
            {
                _node = node;
                _parentObserver = parentObserver;
                ((INotifyCollectionChanged)_node.Links).CollectionChanged += OnLinksChanged;

                foreach (var link in _node.Links)
                    if (link.FirstNode == _node)
                        _parentObserver.OnLinkAdded(link);
            }

            private void OnLinksChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                CheckNotDisposed();

                Link oldLink = null;
                Link newLink = null;

                switch (e.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        newLink = (Link)e.NewItems[0];
                        if (newLink.FirstNode == _node)
                            _parentObserver.OnLinkAdded((Link)e.NewItems[0]);
                        break;

                    case NotifyCollectionChangedAction.Remove:
                        oldLink = (Link)e.OldItems[0];
                        if (oldLink.FirstNode == _node)
                            _parentObserver.OnLinkRemoved((Link)e.OldItems[0]);
                        break;

                    case NotifyCollectionChangedAction.Replace:
                        oldLink = (Link)e.OldItems[0];
                        if (oldLink.FirstNode == _node)
                            _parentObserver.OnLinkRemoved((Link)e.OldItems[0]);

                        newLink = (Link)e.NewItems[0];
                        if (newLink.FirstNode == _node)
                            _parentObserver.OnLinkAdded((Link)e.NewItems[0]);
                        break;

                    case NotifyCollectionChangedAction.Reset:
                        throw new NotImplementedException("MindMapObserver does not support Reset notifications from the MindMap");
                }
            }

            public void Dispose()
            {
                if (_disposed)
                    return;

                ((INotifyCollectionChanged)_node.Links).CollectionChanged -= OnLinksChanged;
                _disposed = true;

                foreach (var link in _node.Links)
                    if (link.FirstNode == _node)
                        _parentObserver.OnLinkRemoved(link);
            }

            private void CheckNotDisposed()
            {
                if (_disposed)
                    throw new ObjectDisposedException("NodeObserver");
            }
        }

    }

    public class NodeEventArgs : EventArgs
    {
        private readonly Node _node;

        public NodeEventArgs(Node node)
        {
            Guard.ArgumentNotNull(node, "node");
            _node = node;
        }

        public Node Node
        {
            get { return _node; }
        }
    }

    public class LinkEventArgs : EventArgs
    {
        private readonly Link _link;

        public LinkEventArgs(Link link)
        {
            Guard.ArgumentNotNull(link, "link");
            _link = link;
        }

        public Link Link
        {
            get { return _link; }
        }
    }
}
